package com.bridgeintelligent.tag.webserver.dim.mgmt.service.dimfree;

import com.bridgeintelligent.tag.constants.ExceptionCodes;
import com.bridgeintelligent.tag.constants.Permissions;
import com.bridgeintelligent.tag.constants.TagConstants;
import com.bridgeintelligent.tag.customer.service.CustomersService;
import com.bridgeintelligent.tag.mapper.*;
import com.bridgeintelligent.tag.user.mgmt.pojo.User;
import com.bridgeintelligent.tag.user.query.service.UserQueryService;
import com.bridgeintelligent.tag.utils.DateHelper;
import com.bridgeintelligent.tag.utils.SecurityHelper;
import com.bridgeintelligent.tag.webserver.dim.mgmt.api.*;
import com.bridgeintelligent.tag.webserver.dim.mgmt.service.dim.DimService;
import com.bridgeintelligent.tag.webserver.dim.mgmt.service.dim.IDimService;
import com.bridgeintelligent.tag.webserver.dim.mgmt.service.mq.SendMsgHandler;
import com.bridgeintelligent.tag.webserver.workflow.*;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wayneleo.quickstart.framework.IDGenerator;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 自定标签审批服务层实现
 */
@Service
@AllArgsConstructor
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class DimFreeApprovalService implements IDimFreeApprovalService {

    private SubmitterService submitterService;
    private ApproverService approverService;
    private DimFreeService dimFreeService;
    private IDimService iDimService;
    private DimFreeMapper dimFreeMapper;
    private SendMsgHandler sendMsgHandler;
    private DimMapper dimMapper;
    private DimThemeMapper dimThemeMapper;
    private UserQueryService userQueryService;
    private DimService dimService;
    private DimItemMapper dimItemMapper;
    private DimFreeApprovalMapper dimFreeApprovalMapper;
    private CustomersService customersService;
    private CatalogMapper catalogMapper;

    /**
     * 新增自定义标签审批通过
     *
     * @param dimId
     */
    @Override
    public void addPass(String dimId) {
        Instance instance = findInstance(dimId);
        Instance pass = approverService.pass(instance.getId());
        //修改审批状态
        String date = DateHelper.currentDateTime();
        dimFreeService.updateApproveState(dimId, Integer.toString(pass.getCurrentStatus()), date);
        //新建成功,默认为审批状态
        dimService.start("01", dimId);
        Map<String, String> map = new HashMap<>();
        DimCatalog catalog = dimFreeMapper.findCatalogName(TagConstants.PRIVATE_CATALOGID);
        map.put("catalogId", catalog.getId());
        map.put("dimId", dimId);
        dimFreeMapper.updCatalog(map);
        //审核通过后文件备份Hdfs
        sendMsgHandler.sendFileBakUpMsg(dimMapper.detail(dimId).getCustList());
    }

    @Override
    public void addSubmit(String dimId) {
        submitterService.submit(new SubmitterService.SubmitParam().setResourceId(dimId)
                                                                  .setWorkflowId(TagConstants.Workflow.ID_10001));
        dimFreeService.updateApprovaleState(dimId, "2");
    }

    /**
     * 审批驳回
     *
     * @param dimId
     */
    @Override
    public void reject(String dimId, String desc) {
        Instance instance = findInstance(dimId);
        Instance reject = approverService.reject(instance.getId(), desc);
        //修改审批状态
        dimFreeService.updateApprovaleState(dimId, Integer.toString(reject.getCurrentStatus()));
    }

    /**
     * 重新提交审批
     *
     * @param dimId
     */
    @Override
    public void resubmit(String dimId) {
        Map<String, Instance> map = submitterService.fetchByResources(new SubmitterService.FetchByResourcesParam().addResourceId(
                dimId)
                                                                                                                  .setContainsDeleted(
                                                                                                                          false)
                                                                                                                  .setCurrentStatus(
                                                                                                                          Status.REJECTED.code()));
        Instance instance = map.get(dimId);
        Instance submit = submitterService.submit(new SubmitterService.SubmitParam().setInstanceId(instance.getId())
                                                                                    .setResourceId(dimId)
                                                                                    .setWorkflowId(instance.getWorkflowId()));
        //修改审批状态
        dimFreeService.updateApprovaleState(dimId, Integer.toString(submit.getCurrentStatus()));
    }

    /**
     * 删除自定义标签审批通过
     *
     * @param dimId
     */
    @Override
    public void delPass(String dimId) {
        Instance instance = findInstance(dimId);
        Instance pass = approverService.pass(instance.getId());
        //修改审批状态
        dimFreeService.updateApprovaleState(dimId, Integer.toString(pass.getCurrentStatus()));
        //删除自定义标签
        iDimService.del(dimId);
    }

    /**
     * 自定义标签清除数据审批通过
     *
     * @param dimId
     */
    @Override
    public void clePass(String dimId) {
        Instance instance = findInstance(dimId);
        Instance pass = approverService.pass(instance.getId());
        //修改审批状态
        dimFreeService.updateApprovaleState(dimId, Integer.toString(pass.getCurrentStatus()));
        //数据清除
        sendMsgHandler.sendMsg(dimId, 3);
        dimMapper.updateDimDataRunning(dimId, true,"0");
    }

    /**
     * 修改自定义标签审批通过
     *
     * @param dimId
     */
    @Override
    public void updatePass(String dimId) {
        Instance instance = findInstance(dimId);
        Instance pass = approverService.pass(instance.getId());
        //修改审批状态
        dimFreeService.updateApprovaleState(dimId, Integer.toString(pass.getCurrentStatus()));
        List<DimDataApproval> approvalList = dimFreeApprovalMapper.findApprovalList(dimId);
        if (!CollectionUtils.isEmpty(approvalList)) {
            DimDataApproval dimFreeModel = approvalList.get(0);
            DimData dimData = new DimData();
            dimData.setDimId(dimFreeModel.getDimId())
                   .setDimName(dimFreeModel.getDimName())
                   .setDefinition(dimFreeModel.getDefinition())
                   .setScenarios(dimFreeModel.getScenarios())
                   .setCustAmount(dimFreeModel.getCustAmount())
                   .setCaliber(dimFreeModel.getCaliber())
                   .setValidTime(dimFreeModel.getValidTime())
                   .setUptTime(DateHelper.currentDateTime());
            dimFreeMapper.updateBaseInfo(dimData);
        }
    }

    /**
     * 获取审批列表
     *
     * @param pageNumber
     * @param pageSize
     * @param theme
     * @param dimName
     * @param approveType
     * @param approveState
     * @param createTimeStart
     * @param createTimeEnd
     * @param uptTimeStart
     * @param uptTimeEnd
     */
    @Override
    public DimPage<DimData> findList(Integer pageNumber, Integer pageSize, String theme, String dimName, String approveType, String approveState, String createTimeStart, String createTimeEnd, String uptTimeStart, String uptTimeEnd) {
        //获取权限id
        List<String> workflowIds = findInstanceByPower(approveType);
        if (CollectionUtils.isEmpty(workflowIds)) {
            workflowIds.add(IDGenerator.gen());
        }
        Map map = new HashMap();
        map.put("theme", theme);
        map.put("dimName", dimName);
        map.put("approveState", approveState);
        map.put("createTimeStart", createTimeStart);
        if (createTimeEnd != null && !"".equals(createTimeEnd)) {
            map.put("createTimeEnd", createTimeEnd + "23.59.59");
        }
        map.put("uptTimeStart", uptTimeStart);
        if (uptTimeEnd != null && !"".equals(uptTimeEnd)) {
            map.put("uptTimeEnd", uptTimeEnd + "23.59.59");
        }
        map.put("workflowIds", workflowIds);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(calendar.MONTH, -2);
        String temp = format(calendar.getTime());
        Page page = PageHelper.startPage(pageNumber, pageSize);
        List<DimData> list = dimFreeMapper.findApproveList(map);
        if (CollectionUtils.isNotEmpty(list)) {
            for (DimData dimData : list) {
                if (Integer.toString(Status.WAITTING.code())
                           .equals(dimData.getApproveState())) {
                    dimData.setApproveStateName(Status.WAITTING.info());
                } else if (Integer.toString(Status.REJECTED.code())
                                  .equals(dimData.getApproveState())) {
                    dimData.setApproveStateName(Status.REJECTED.info());
                } else if (Integer.toString(Status.PASSED.code())
                                  .equals(dimData.getApproveState())) {
                    dimData.setApproveStateName(Status.PASSED.info());
                }
                //dimData.setThemeCNName(dimThemeMapper.findOne(dimData.getTheme()));
                dimData.setCreaterCNName(userQueryService.findOneByUserId(dimData.getCreaterId()));
                if (temp.compareTo(dimData.getUptTime()) < 1) {
                    dimData.setIsnew(true);
                } else {
                    dimData.setIsnew(false);
                }
                DimData db = dimFreeMapper.findByDimId(dimData.getDimId());
                if (db != null) {
                    dimData.setScenarios(db.getScenarios());
                    if (db.getCatalogId() != null && db.getCatalogId() != "") {
                        dimData.setCatalogName(catalogMapper.getName(dimData.getCatalogId()));
                    }
                }
            }
        }
        DimPage<DimData> dimDimPage = new DimPage<>();
        dimDimPage.setContent(list);
        dimDimPage.setTotalPages(page.getPages());
        dimDimPage.setTotalElements(page.getTotal());
        dimDimPage.setSize(page.getPageSize());
        dimDimPage.setRequestPager(pageNumber);
        return dimDimPage;
    }

    /**
     * 获取所有的申请类型
     */
    @Override
    public Map findApproveType() {
        Map map = new HashMap();
        map.put(TagConstants.Workflow.ID_10001,
                Permissions.of(TagConstants.Workflow.ID_10001)
                           .getName());
       /* map.put(TagConstants.Workflow.ID_10002, Permissions.of(TagConstants.Workflow.ID_10002).getName());
        map.put(TagConstants.Workflow.ID_10003, Permissions.of(TagConstants.Workflow.ID_10003).getName());
        map.put(TagConstants.Workflow.ID_10004, Permissions.of(TagConstants.Workflow.ID_10004).getName());
        map.put(TagConstants.Workflow.ID_10005, Permissions.of(TagConstants.Workflow.ID_10005).getName());
        map.put(TagConstants.Workflow.ID_10006, Permissions.of(TagConstants.Workflow.ID_10006).getName());*/
        return map;
    }

    /**
     * 上传新增通过
     *
     * @param dimId
     */
    @Override
    public void fileAddPass(String dimId) {
        Instance instance = findInstance(dimId);
        Instance pass = approverService.pass(instance.getId());
        //修改审批状态
        dimFreeService.updateApprovaleState(dimId, Integer.toString(pass.getCurrentStatus()));
        //执行新增
        sendMsgHandler.sendMsg(dimId, 2);
        dimMapper.updateDimDataRunning(dimId, true,"0");
    }

    /**
     * 上传删除通过
     *
     * @param dimId
     */
    @Override
    public void fileDeletePass(String dimId) {
        Instance instance = findInstance(dimId);
        Instance pass = approverService.pass(instance.getId());
        //修改审批状态
        dimFreeService.updateApprovaleState(dimId, Integer.toString(pass.getCurrentStatus()));
        //执行删除
        sendMsgHandler.sendMsg(dimId, 1);
        dimMapper.updateDimDataRunning(dimId, true,"0");
    }

    /**
     * 获取流程实例对象
     *
     * @param dimId
     * @return
     */
    public Instance findInstance(String dimId) {
        Map<String, Instance> map = submitterService.fetchByResources(new SubmitterService.FetchByResourcesParam().addResourceId(
                dimId)
                                                                                                                  .setContainsDeleted(
                                                                                                                          false)
                                                                                                                  .setCurrentStatus(
                                                                                                                          Status.WAITTING.code()));
        Set<Map.Entry<String, Instance>> entries = map.entrySet();
        for (Map.Entry<String, Instance> e : entries) {
            String resource = e.getValue()
                               .getResource();
            System.out.println("测试打印================1" + resource);
            System.out.println("测试打印================2" + e.getValue()
                                                          .getId());
        }
        Instance instance = map.get(dimId);
        return instance;
    }

    /**
     * 获取用户有权审批的流程实例
     *
     * @return
     */
    public List<String> findInstanceByPower(String workflowId) {
        List<String> workflowIds = new ArrayList<>();
        if (StringUtils.isEmpty(workflowId)) {
            for (String workflowDefinitionId : TagConstants.Workflow.values()) {
                if (SecurityHelper.containsPermission(workflowDefinitionId)) {
                    workflowIds.add(workflowDefinitionId);
                }
            }
        } else {
            if (!SecurityHelper.containsPermission(workflowId)) {
                User user = SecurityHelper.currentUser();
                throw new WorkflowException((ExceptionCodes.WORKFLOW_20006.args(user.getUserId(), workflowId)));
            }
            workflowIds.add(workflowId);
        }
        return workflowIds;
    }

    private static String format(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return sdf.format(date);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 设置标签项
     *
     * @param dimId
     * @param time
     * @return
     */
    private DimItem setDimItem(String dimId, String time) {
        DimItem dimItem = new DimItem();
        dimItem.setId(IdWorker.nextId());
        dimItem.setItemNo("0");
        dimItem.setId(dimId);
        dimItem.setDimId(dimId);
        dimItem.setUpdateDate(time);
        dimItem.setItemName("是");
        return dimItem;
    }
}
